var os = require('os');
var fs = require('fs');
var config = require('../config');


var Setting = function (data) {
    this.data = data ;
};

var pf = os.platform().toString();
var file =  __dirname + (pf == 'win32' ? '\\' : '/') + 'config.json';
fs.openSync(file, 'a');

var doInit = function(){
    var str = fs.readFileSync(file, 'UTF-8');
    if(str == '' || str == undefined){
        str = '{}';
    }
    var data = JSON.parse(str);

    //挑战成功百分比
    if(data['succPct'] == undefined){
        data['succPct'] = 60;
    }

    //破纪录获悬赏分比例
    if(data['breakRecordPct'] == undefined){
        data['breakRecordPct'] = 10;
    }

    //每题默认分数
    if(data['score'] == undefined){
        data['score'] = 2;
    }

    //最少参战人数
    if(data['minNum'] == undefined){
        data['minNum'] = 3;
    }

    //最多参战人数
    if(data['maxNum'] == undefined){
        data['maxNum'] = 5;
    }

    //参战报名积分
    if(data['enrollScore'] == undefined){
        data['enrollScore'] = 5;
    }

    //题库试卷数量
    if(data['paperNum'] == undefined){
        data['paperNum'] = 200;
    }

    //试卷题目数量
    /*if(data['questionNum'] == undefined){
        data['questionNum'] = 50;
    }*/

    //保存
    doSave(data);

    return data;
};

var doSave = function (data) {
    var str = JSON.stringify(data);
    fs.writeFileSync(file, str, 'UTF-8');
};

Setting.prototype.init = function(){
    this.data = doInit();
};

Setting.prototype.save = function(){
    doSave(this.data);
};

Setting.prototype.set = function(key, value){
    this.data[key] = value;
    this.save();
};

Setting.prototype.get = function(key){
    return this.data[key];
};

Setting.prototype.getData = function(){
    return this.data;
};

var setting = new Setting(doInit());

//定时从文件刷新数据
var i = 1;
if(config.refreshFrequency > 0){
    setInterval(function(){
        setting.init();
        console.log('第' + (i++) + '次读取配置信息，时间：' + ( new Date() ) + '，刷新频率：' + config.refreshFrequency + 'MS');
    }, config.refreshFrequency);
}

module.exports = setting;
